package com.begamer.card.model.dao;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.begamer.card.model.pojo.Model;

public class ModelDao extends HibernateDaoSupport {
	
	private static final Log log = LogFactory.getLog(Model.class);
	
	public void addModel(Model model)
	{
		log.debug("saving Model instance");
		try
		{
			getHibernateTemplate().save(model);
			log.debug("save Model successful");
		}
		catch (RuntimeException e)
		{
			log.error("save Model failed", e);
			throw e;
		}
	}
	
	public void delModelTrue(Model model)
	{
		log.debug("deleting(true) Model instance");
		Session session = getSession();
		try
		{
			Query query = session.createQuery("delete from Privilege p where p.accessValue=?");
			query.setInteger(0, model.getM_id());
			query.executeUpdate();
			getHibernateTemplate().delete(model);
			log.debug("delete successful");
		}
		catch (RuntimeException e)
		{
			log.error("delete failed", e);
			throw e;
		}
	}
	
	public void delModelFalse(int id, int logo)
	{
		log.debug("deleting(false) Model instance");
		Session session = getSession();
		try
		{
			String hql = "udpate Model m set m.logo=? where m.id=?";
			Query query = session.createQuery(hql);
			query.setInteger(0, logo);
			query.setInteger(1, id);
			query.executeUpdate();
			log.debug("delete successful");
		}
		catch (RuntimeException e)
		{
			log.error("delete failed", e);
			throw e;
		}
		finally
		{
			session.close();
		}
	}
	
	public void upModel(Model model)
	{
		log.debug("merging Model instance");
		try
		{
			getHibernateTemplate().merge(model);
			log.debug("merge successful");
		}
		catch (RuntimeException e)
		{
			log.error("merge failed", e);
			throw e;
		}
	}
	
	@SuppressWarnings("unchecked")
	public List<Model> findAllModel()
	{
		log.debug("finding All Model instance");
		try
		{
			String queryString = "from Model m";
			return getHibernateTemplate().find(queryString);
		}
		catch (RuntimeException e)
		{
			log.error("find failed", e);
			throw e;
		}
	}
	
	public Model oneModel(int id)
	{
		log.debug("finding One Model instance");
		try
		{
			Model model = (Model) getHibernateTemplate().get(Model.class, id);
			log.debug("find successful");
			return model;
		}
		catch (RuntimeException e)
		{
			log.error("find failed", e);
			throw e;
		}
	}
	
}
